<script lang="ts" setup>
/**
 * axios axios 配置
 * myMixin 页面公共方法
 */
let axios: any = inject('$axios');
import useClipboard from 'vue-clipboard3';
const { toClipboard } = useClipboard();
import { useRouter } from 'vue-router';
const router = useRouter();

/**
 * tab 切换
 */
const iindex = ref(0);
const FollowForm = ref(['待回访', '超时', '已回访']);
const handelTabBtn = (index) => {
  iindex.value = index;
  activeColumns.value = index;
  tableRef.value.moveDoLayout();
  getTableList(1);
};

/**
 * searchForm 搜索value
 * searchOptions 搜索配置
 * handelSearch 搜索暴露方法
 */
const searchOptions = reactive([
  {
    label: '信息编号',
    value: '',
    key: 'no',
    placeholder: '请输入信息编号',
    options: [],
    type: 'input',
    size: 5,
  },
  {
    label: '信息类型',
    value: '',
    key: 'cat_1',
    placeholder: '请选择信息类型',
    options: [],
    type: 'select',
    size: 5,
  },
  {
    label: '微信号',
    value: '',
    key: 'number',
    placeholder: '请输入微信号',
    options: [],
    type: 'input',
    size: 5,
  },
  {
    label: '发布地区',
    value: '',
    key: 'areaDate',
    placeholder: '请选择信息发布地区',
    options: [],
    type: 'city',
    size: 5,
  },
]);
const searchItem = ref();
const searchForm = ref();
const handelSearch = (params) => {
  searchForm.value = Object.assign(
    {
      no: '', // 信息编号
      cat_1: '', // 信息类型
      number: '', // 微信号
      areaDate: '', // 发布地区
    },
    params,
  );
  // 省市区数据
  if (params.areaDate.length) {
    searchForm.value.area = params.areaDate[0];
    searchForm.value.city = params.areaDate[1];
    searchForm.value.address = params.areaDate[2];
    delete searchForm.value.areaDate;
  }
  getTableList();
};

/**
 * 列表表格：
 * tableOptions 表格组件配置
 * tableData 表格数据参数
 * loadingTable 加载表格数据loading
 * getTableList 获取表格数据方法
 * handlePaginationChange 切换currentPage或切换pageSize
 */
const tableOptions = reactive({
  showPagination: true,
  defaultSort: { prop: 'plain_end_time', order: 'descending' },
  paginationConfig: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
});
const tableRef = ref();
const activeColumns: any = ref('0');
// 待回访
const columnsWait = ref([
  { prop: 'no', label: '信息编号', align: 'center', width: '160' },
  {
    label: '订单类型',
    align: 'center',
    render: ({ row }) => {
      return h('span', row.style == 1 ? '普通' : 'VIP');
    },
  },
  {
    label: '是否付费',
    align: 'center',
    render: ({ row }) => {
      return h('span', row.is_pay == 1 ? '是' : '否');
    },
  },
  { prop: 'cat_1_msg', label: '信息类型', align: 'center' },
  {
    label: '发布地区',
    align: 'center',
    render: ({ row }) => {
      return h('span', `${row.area_whole_msg}`);
    },
  },
  {
    label: '用户',
    align: 'center',
    width: '250',
    render: ({ row }) => {
      if (!row.nickname && !row.number) {
        return h(ElLink, { type: 'primary' }, '催促');
      }
      return h(
        'div',
        {
          style: {
            height: '100%',
            width: '90%',
            margin: '0 auto',
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'center',
          },
        },
        [
          h(
            'div',
            {
              style: {
                height: '100%',
                width: '85%',
                overflow: 'hidden',
                'white-space': 'nowrap',
                'text-overflow': 'ellipsis',
                margin: '0 auto',
                'text-align': 'left',
              },
            },
            [
              h(
                'p',
                {
                  style: {
                    width: '100%',
                    overflow: 'hidden',
                    'white-space': 'nowrap',
                    'text-overflow': 'ellipsis',
                    'line-height': '15px',
                    'margin-bottom': '3px',
                  },
                },
                '微信昵称：' + row.nickname || '',
              ),
              h(
                'p',
                { style: { 'line-height': '15px' } },
                '微信号：' + row.number || '',
              ),
            ],
          ),
          h(
            ElButton,
            {
              type: 'primary',
              size: 'small',
              style: {
                marginLeft: '10px',
                width: '35px',
              },
              onClick: () => handelCopy(row),
            },
            '复制',
          ),
        ],
      );
    },
  },
  {
    prop: 'plain_end_time',
    label: '计划结束时间',
    align: 'center',
    width: '180',
    sortable: 'true',
    type: 'date'
  },
  { prop: 'created_at', label: '创建时间', align: 'center', width: '180' },
  {
    label: '操作',
    align: 'center',
    width: '200',
    render: ({ row }) => {
      let arr = [
        {
          name: '查看',
          type: 'primary',
          icon: '',
          command: handelWatch,
        },
        {
          name: '回访记录',
          type: 'primary',
          icon: '',
          command: handelRecord,
        },
      ];
      let showButton = arr.map((item) => {
        return h(
          ElButton,
          {
            type: item.type,
            icon: item.icon,
            text: true,
            style: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'start',
              height: '25px',
              width: '50%',
              margin: '0  5px',
              padding: 0,
            },
            onClick: () => item.command(row),
          },
          item.name,
        );
      });
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            width: '70%',
            height: '100%',
            margin: '0 auto',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          },
        },
        showButton,
      );
    },
  },
]);
// 超时
const columnsTimeout = ref([
  { prop: 'no', label: '信息编号', align: 'center', width: '160' },
  { prop: 'cat_1_msg', label: '信息类型', align: 'center', width: '140' },
  {
    label: '发布地区',
    align: 'center',
    render: ({ row }) => {
      return h('span', `${row.area_whole_msg}`);
    },
  },
  {
    label: '用户',
    width: '250',
    align: 'center',
    render: ({ row }) => {
      if (!row.nickname && !row.number) {
        return h(ElLink, { type: 'primary' }, '催促');
      }
      return h(
        'div',
        {
          style: {
            height: '100%',
            width: '90%',
            margin: '0 auto',
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'center',
          },
        },
        [
          h(
            'div',
            {
              style: {
                height: '100%',
                width: '85%',
                overflow: 'hidden',
                'white-space': 'nowrap',
                'text-overflow': 'ellipsis',
                margin: '0 auto',
                'text-align': 'left',
              },
            },
            [
              h(
                'p',
                {
                  style: {
                    width: '100%',
                    overflow: 'hidden',
                    'white-space': 'nowrap',
                    'text-overflow': 'ellipsis',
                    'line-height': '15px',
                    'margin-bottom': '3px',
                  },
                },
                '微信昵称：' + row.nickname || '',
              ),
              h(
                'p',
                { style: { 'line-height': '15px' } },
                '微信号：' + row.number || '',
              ),
            ],
          ),
          h(
            ElButton,
            {
              type: 'primary',
              size: 'small',
              style: {
                marginLeft: '10px',
                width: '35px',
              },
              onClick: () => handelCopy(row),
            },
            '复制',
          ),
        ],
      );
    },
  },
  {
    prop: 'plain_end_time',
    label: '计划结束时间',
    align: 'center',
    sortable: 'true',
    width: '200',
    type: 'date',
  },
  { prop: 'created_at', label: '创建时间', align: 'center', width: '180' },
  {
    prop: 'visit_day',
    label: '超时天数（天）',
    align: 'center',
  },
  {
    label: '操作',
    align: 'center',
    width: '200',
    render: ({ row }) => {
      let arr = [
        // {
        //   name: '重新发布',
        //   type: 'primary',
        //   icon: '',
        //   command: handelRepublish,
        // },
        {
          name: '查看',
          type: 'primary',
          icon: '',
          command: handelWatch,
        },
        {
          name: '回访记录',
          type: 'primary',
          icon: '',
          command: handelRecord,
        },
      ];
      let showButton = arr.map((item) => {
        return h(
          ElButton,
          {
            type: item.type,
            icon: item.icon,
            text: true,
            style: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'start',
              height: '25px',
              width: '50%',
              margin: '0  5px',
              padding: 0,
            },
            onClick: () => item.command(row),
          },
          item.name,
        );
      });
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            width: '70%',
            height: '100%',
            margin: '0 auto',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          },
        },
        showButton,
      );
    },
  },
]);
// 已回访
const columnsOk = ref([
  { prop: 'no', label: '信息编号', align: 'center', width: '160' },
  { prop: 'cat_1_msg', label: '信息类型', align: 'center', width: '140' },
  {
    label: '发布地区',
    align: 'center',
    width: '220',
    render: ({ row }) => {
      return h('span', `${row.area_whole_msg}`);
    },
  },
  {
    label: '用户',
    width: '250',
    align: 'center',
    render: ({ row }) => {
      if (!row.nickname && !row.number) {
        return h(ElLink, { type: 'primary' }, '催促');
      }
      return h(
        'div',
        {
          style: {
            height: '100%',
            width: '90%',
            margin: '0 auto',
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'center',
          },
        },
        [
          h(
            'div',
            {
              style: {
                height: '100%',
                width: '85%',
                overflow: 'hidden',
                'white-space': 'nowrap',
                'text-overflow': 'ellipsis',
                margin: '0 auto',
                'text-align': 'left',
              },
            },
            [
              h(
                'p',
                {
                  style: {
                    width: '100%',
                    overflow: 'hidden',
                    'white-space': 'nowrap',
                    'text-overflow': 'ellipsis',
                    'line-height': '15px',
                    'margin-bottom': '3px',
                  },
                },
                '微信昵称：' + row.nickname || '',
              ),
              h(
                'p',
                { style: { 'line-height': '15px' } },
                '微信号：' + row.number || '',
              ),
            ],
          ),
          h(
            ElButton,
            {
              type: 'primary',
              size: 'small',
              style: {
                marginLeft: '10px',
                width: '35px',
              },
              onClick: () => handelCopy(row),
            },
            '复制',
          ),
        ],
      );
    },
  },
  {
    prop: 'plain_end_time',
    label: '计划结束时间',
    align: 'center',
    sortable: 'true',
    width: '180',
    type: 'date'
  },
  { prop: 'created_at', label: '创建时间', align: 'center', width: '180' },
  { prop: 'visit_time', label: '回访时间', align: 'center', width: '180', type: 'date' },
  {
    label: '操作',
    align: 'center',
    render: ({ row }) => {
      let arr = [
        {
          name: '查看',
          type: 'primary',
          icon: '',
          command: handelWatch,
        },
        // {
        //   name: '回访记录',
        //   type: 'primary',
        //   icon: 'View',
        //   command: handelRecord,
        // },
      ];
      let showButton = arr.map((item) => {
        return h(
          ElButton,
          {
            type: item.type,
            icon: item.icon,
            text: true,
            style: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'start',
              height: '25px',
              width: '50%',
              margin: '0  5px',
              padding: 0,
            },
            onClick: () => item.command(row),
          },
          item.name,
        );
      });
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            width: '70%',
            height: '100%',
            margin: '0 auto',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          },
        },
        showButton,
      );
    },
  },
]);
const tableData = ref([]);
const loadingTable = ref(false);
const getTableList = async (page?: any) => {
  loadingTable.value = true;
  let params = Object.assign(
    {
      page: page ? page : tableOptions.paginationConfig.currentPage,
      limit: tableOptions.paginationConfig.pageSize,
      visit_status: iindex.value == 0 ? 1 : iindex.value == 1 ? 3 : 2, // 1待回访 2已回访 3回访超时
      is_order_plain_end_time: tableSort.value,
    },
    searchForm.value,
  );
  let res = await axios.getVisitList(params);
  loadingTable.value = false;
  if (res.data.code != 200) return;
  tableData.value = res.data.data.list;
  tableOptions.paginationConfig = {
    total: Number(res.data.data.pageData.count),
    currentPage: Number(res.data.data.pageData.page),
    pageSize: 10,
  };
};
const handlePaginationChange = (currentPage, pageSize) => {
  tableOptions.paginationConfig.currentPage = currentPage;
  tableOptions.paginationConfig.pageSize = pageSize;
  getTableList();
};
const tableSort = ref(2);
const handleSortChange = (column, prop, order) => {
  if (order == 'ascending') {
    tableSort.value = 1;
  } else if (order == 'descending') {
    tableSort.value = 2;
  }
  getTableList();
};

/**
 * 表格操作方法
 * handelWatch 查看
 * handelCopy 复制
 */
const handelWatch = (row) => {
  if (!row.rpc_id)
    return ElMessage({
      type: 'warning',
      message: `快捷信息请先在任务管理编辑后查看`,
    });
  let obj = JSON.parse(JSON.stringify(row));
  router.push({
    name: 'backVisitDetail',
    state: {
      obj,
    },
  });
};
const handelCopy = async (row) => {
  if (!row.number) return ElMessage.warning('暂无信息可复制！');
  await toClipboard(`${row.number}`);
  ElMessage.success('复制成功！');
};

/**
 * 回访记录
 */
const dialogRecordOpitons = reactive({
  dialogShow: false,
  title: '回访记录',
  width: '45%',
  footButtonList: {
    cancel: {
      type: 'cancel',
      buttonType: 'default',
      btnText: '取 消',
      btnLoading: false,
      btnLoadingText: '',
    },
    success: {
      type: 'success',
      buttonType: 'primary',
      btnText: '确 认',
      btnLoading: false,
      btnLoadingText: '提交中',
    },
  },
});
const formRecordOptions = reactive({
  labelWidth: '55px',
  labelPosition: 'left',
});
const formRecord: any = ref({
  visit_score: '',
  visit_appraise: '',
});
const recordFormRef = ref();
const rulesRecord = reactive({
  visit_score: [
    {
      required: true,
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) return callback(new Error('请选择评价'));
        callback();
      },
      trigger: ['blur'],
    },
  ],
  visit_appraise: [
    {
      required: true,
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) return callback(new Error('请填写内容'));
        if (value.length > 200) return callback(new Error('最多200个字符'));
        callback();
      },
      trigger: ['blur'],
    },
  ],
});
const editRecordInfo = ref();
const handelRecord = (row) => {
  editRecordInfo.value = row;
  formRecord.value = {
    visit_score: row.visit_score,
    visit_appraise: row.visit_appraise,
  };
  dialogRecordOpitons.dialogShow = true;
};
const handelDialogRecordButton = (item) => {
  if (item.type == 'cancel') dialogRecordOpitons.dialogShow = false;
  if (item.type == 'success') handleRecordSuccess('success');
};
const handleRecordSuccess = async (type) => {
  recordFormRef.value.validateForm(async (valid) => {
    if (valid) {
      dialogRecordOpitons.footButtonList[type].btnLoading = true;
      let res = await axios.createVisitLog({
        id: editRecordInfo.value.id,
        visit_score: formRecord.value.visit_score,
        visit_appraise: formRecord.value.visit_appraise,
      });
      dialogRecordOpitons.footButtonList[type].btnLoading = false;
      if (res.data.code != 200) return;
      ElMessage({ type: 'success', message: `操作成功` });
      dialogRecordOpitons.dialogShow = false;
      getTableList();
    }
  });
};

/**
 * 重新发布
 */
const handelRepublish = (row) => {
  ElMessageBox.confirm('确认要重新发布任务吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action == 'confirm') {
        //点击确认请求接口
        let res: any = await axios.getVisitHandle({
          id: row.id,
          style: 1
        });
        if (res.data.code != 200) return;
        ElMessage({ type: 'success', message: `发布成功` });
        done();
      } else {
        //点击取消关闭
        done();
      }
    },
  });
}

/**
 * init 初始化方法入口
 */
const areaOptions = ref();
const init = async () => {
  // 信息类型数据
  let infoType = await axios.getTableTag();
  let arr = infoType.data.data.map((item) => {
    item.label = item.name;
    item.value = item.id;
    return item;
  });
  searchItem.value.handelSetOptions(arr, 1);

  // 地区数据
  let cityDate = await axios.getCityChina({
    is_tree: 1,
  });
  areaOptions.value = cityDate.data.data;
  searchItem.value.handelSetOptions(cityDate.data.data, 3);
  getTableList();
};
init();
</script>
<template>
  <div class="backVisit">
    <!-- tab切换 -->
    <div class="followtab padding-20">
      <div class="followup">
        <div class="tabbtn" v-for="(item, index) in FollowForm" :key="index" :style="iindex == index
          ? 'background:rgb(24, 145, 255);color:#fff;border:none;'
          : ''
          ">
          <span @click="handelTabBtn(index)">{{ item }}</span>
        </div>
      </div>
    </div>
    <!-- 搜索 、表格数据 -->
    <pagesLayout pagesType="alone" class="padding-20">
      <template #center>
        <div class="pageslayout">
          <!-- 搜索 -->
          <div class="pageslayoutHeader">
            <SearchItem :searchOptions="searchOptions" @handelSearch="handelSearch" ref="searchItem"></SearchItem>
          </div>
          <!-- 、表格数据 -->
          <div class="pageslayoutContaint" v-loading="loadingTable" element-loading-text="加载中...">
            <Table :columns="columnsWait" v-if="activeColumns == 0" :table-data="tableData" :options="tableOptions"
              style="height: calc(100% - 79.39px)" ref="tableRef" @sort-change="handleSortChange"
              @handel-pagination-change="handlePaginationChange"></Table>
            <Table :columns="columnsTimeout" v-else-if="activeColumns == 1" :table-data="tableData"
              :options="tableOptions" style="height: calc(100% - 79.39px)" ref="tableRef"
              @sort-change="handleSortChange" @handel-pagination-change="handlePaginationChange"></Table>
            <Table :columns="columnsOk" v-else-if="activeColumns == 2" :table-data="tableData" :options="tableOptions"
              style="height: calc(100% - 79.39px)" ref="tableRef" @sort-change="handleSortChange"
              @handel-pagination-change="handlePaginationChange"></Table>
          </div>
        </div>
      </template>
    </pagesLayout>
    <!-- 回访记录 弹窗 -->
    <Dialog :dialog-object="dialogRecordOpitons" @handelDialogButton="handelDialogRecordButton" class="backReload">
      <template v-slot:dialogContaint>
        <Form :form-object="formRecordOptions" :form="formRecord" :rules="rulesRecord" ref="recordFormRef">
          <template v-slot:formContaint>
            <el-form-item label="评价:" prop="visit_score">
              <el-rate v-model="formRecord.visit_score" />
            </el-form-item>
            <el-form-item label="内容:" prop="visit_appraise">
              <el-input v-model="formRecord.visit_appraise" :rows="10" type="textarea" placeholder="限制200字符以内" />
            </el-form-item>
          </template>
        </Form>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="scss">
.backVisit {
  height: 100%;

  .followtab {
    cursor: pointer;

    .followup {
      width: 900px;
      height: 50px;
      display: flex;
      align-items: center;
      color: #222;

      >div:nth-child(1) {
        border-radius: 5px 0 0 5px;
        border-right: none;
      }

      >div:nth-child(3) {
        border-radius: 0 5px 5px 0;
        border-left: none;
      }

      .tabbtn {
        height: 31px;
        width: 100px;
        border: 1px solid #cccccc;

        >span {
          height: 100%;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .backReload {
    ::v-deep .el-dialog__header {
      p {
        color: #3c3c3c !important;
      }
    }
  }
}
</style>
